import api from '@/http/api';
import Rsa from '@/utils/rsa.js';
import router from '@/router';
let lastTime = new Date().getTime();
let currentTime = new Date().getTime();
let timeOut = 15 * 60 * 1000; //设置超时时间: 5分钟
window.onload = function() {
  window.document.onmousedown = function() {
    let token = sessionStorage.getItem('token');
    // 保存最新的操作时间到storage中
    if (token) {
      sessionStorage.setItem('lastTime', new Date().getTime());
    }
  };
};
/**
 *
 * @returns asdf
 */
async function checkTimeout() {
  let token = sessionStorage.getItem('token');
  let timestamp = sessionStorage.getItem('timestamp');

  if (!token) return;
  //更新当前时间
  currentTime = new Date().getTime();
  lastTime = sessionStorage.getItem('lastTime');
  //判断是否超时
  if (currentTime - lastTime > timeOut) {
    // 清除storage的数据(登陆信息和token)
    sessionStorage.clear();
    sessionStorage.setItem('lastTime', new Date().getTime());
    router.push('/login');
    // 移除cookie
  } else if (currentTime - timestamp > 23 * 60 * 60 * 1000) {
    // 如果token快过期了,服务器时间减去保存token的服务器时间
    let rsa = new Rsa();
    let aesrsa = rsa.RSAencrypt(rsa.key + rsa.iv);
    let account = sessionStorage.getItem('account');
    let password = sessionStorage.getItem('password');
    let serverTime = await api.user.get_server_timestamp();
    let userInfo = {
      username: rsa.encrypt(account),
      password: rsa.encrypt(password),
      aesrsa: aesrsa,
      timestamp: serverTime,
      sign: this.$md5(`${account}#${password}#${rsa.key + rsa.iv}#${serverTime}`)
    };

    let res = await api.login.login(userInfo);
    if (res.code !== 0) return;
    sessionStorage.setItem('timestamp', new Date().getTime());
    sessionStorage.setItem('token', res.data.token);
    sessionStorage.setItem('keyiv', JSON.stringify({ key: rsa.key, iv: rsa.iv })); // AES key iv
  }
}

export default function() {
  /* 定时器 间隔10秒检测是否长时间未操作页面 */
  window.setInterval(checkTimeout, 60e3);
}
